using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using WhisperWrapper;

public class WhisperExample : MonoBehaviour
{
    [SerializeField]
#if UNITY_STANDALONE_WIN
    public string model = "D:/Documents/cmake/whisper.cpp/models/ggml-base.bin";
#elif UNITY_STANDALONE_OSX
    public string model = "/Volumes/MACBOOK/macbook/Documents/cmake/whisper.cpp/models/ggml-base.bin";
#else
    public string model = "";
#endif
    [SerializeField]
    public string language = "zh";
    [SerializeField]
    public string device = "CPU";

    // Start is called before the first frame update
    void Start()
    {
        // Initialize whisper
        Whisper.Initialize(model, language, device);

        // Run whisper
        string voice = Application.streamingAssetsPath + "/hello.wav";
        StartCoroutine(ReadAudio(voice, (audio, data) =>
        {
            if (data == null) return;
            Whisper.Inference(data);
        }));
    }

    IEnumerator ReadAudio(string path, Action<AudioClip, float[]> action)
    {
        path = "file://" + path;
        AudioType audioType = AudioType.MPEG;
        if (path.Substring(path.LastIndexOf(".") + 1).ToLower() == "wav") audioType = AudioType.WAV;
        using (var uwr = UnityWebRequestMultimedia.GetAudioClip(path, audioType))
        {
            yield return uwr.SendWebRequest();
            AudioClip clip = null;
            if (uwr.result == UnityWebRequest.Result.ConnectionError)
            //if (uwr.isNetworkError)
            {
                Debug.LogError(uwr.error + "(" + path + ")");
            }
            else
            {
                clip = DownloadHandlerAudioClip.GetContent(uwr);
            }
            float[] data = null;
            if (clip != null)
            {
                data = new float[clip.samples * clip.channels];
                clip.GetData(data, 0);
            }
            action?.Invoke(clip, data);
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (WhisperEventHandler.TextFinished())
        {
            string text = WhisperEventHandler.PopText();
            Debug.Log(text);
        }
    }

    void OnDestroy()
    {
        Whisper.Destroy();
    }
}
